import { create } from 'zustand';
import {
  Site,
  Certificate,
  Container,
  CreateSiteRequest,
  CreateCertificateRequest,
  CreateContainerRequest,
  DashboardStats,
} from '../types';
import apiService from '../services/api';

interface BusinessState {
  // 站点相关
  sites: Site[];
  sitesLoading: boolean;
  sitesError: string | null;

  // 证书相关
  certificates: Certificate[];
  certificatesLoading: boolean;
  certificatesError: string | null;

  // 容器相关
  containers: Container[];
  containersLoading: boolean;
  containersError: string | null;

  // 仪表板统计
  dashboardStats: DashboardStats | null;
  statsLoading: boolean;
  statsError: string | null;

  // Actions - 站点
  fetchSites: () => Promise<void>;
  createSite: (siteData: CreateSiteRequest) => Promise<Site>;
  updateSite: (id: number, siteData: Partial<CreateSiteRequest>) => Promise<Site>;
  deleteSite: (id: number) => Promise<void>;

  // Actions - 证书
  fetchCertificates: () => Promise<void>;
  createCertificate: (certData: CreateCertificateRequest) => Promise<Certificate>;
  updateCertificate: (id: number, certData: Partial<CreateCertificateRequest>) => Promise<Certificate>;
  deleteCertificate: (id: number) => Promise<void>;

  // Actions - 容器
  fetchContainers: () => Promise<void>;
  createContainer: (containerData: CreateContainerRequest) => Promise<Container>;
  updateContainer: (id: number, containerData: Partial<CreateContainerRequest>) => Promise<Container>;
  deleteContainer: (id: number) => Promise<void>;

  // Actions - 仪表板
  fetchDashboardStats: () => Promise<void>;

  // Utility actions
  clearErrors: () => void;
}

export const useBusinessStore = create<BusinessState>()((set, get) => ({
  // 初始状态
  sites: [],
  sitesLoading: false,
  sitesError: null,

  certificates: [],
  certificatesLoading: false,
  certificatesError: null,

  containers: [],
  containersLoading: false,
  containersError: null,

  dashboardStats: null,
  statsLoading: false,
  statsError: null,

  // 站点相关Actions
  fetchSites: async () => {
    try {
      set({ sitesLoading: true, sitesError: null });
      const sites = await apiService.getSites();
      set({ sites, sitesLoading: false });
    } catch (error: any) {
      set({
        sitesLoading: false,
        sitesError: error.message || '获取站点列表失败',
      });
    }
  },

  createSite: async (siteData: CreateSiteRequest) => {
    try {
      set({ sitesLoading: true, sitesError: null });
      const newSite = await apiService.createSite(siteData);
      const { sites } = get();
      set({
        sites: [...sites, newSite],
        sitesLoading: false,
      });
      return newSite;
    } catch (error: any) {
      set({
        sitesLoading: false,
        sitesError: error.message || '创建站点失败',
      });
      throw error;
    }
  },

  updateSite: async (id: number, siteData: Partial<CreateSiteRequest>) => {
    try {
      set({ sitesLoading: true, sitesError: null });
      const updatedSite = await apiService.updateSite(id, siteData);
      const { sites } = get();
      set({
        sites: sites.map((site) => (site.id === id ? updatedSite : site)),
        sitesLoading: false,
      });
      return updatedSite;
    } catch (error: any) {
      set({
        sitesLoading: false,
        sitesError: error.message || '更新站点失败',
      });
      throw error;
    }
  },

  deleteSite: async (id: number) => {
    try {
      set({ sitesLoading: true, sitesError: null });
      await apiService.deleteSite(id);
      const { sites } = get();
      set({
        sites: sites.filter((site) => site.id !== id),
        sitesLoading: false,
      });
    } catch (error: any) {
      set({
        sitesLoading: false,
        sitesError: error.message || '删除站点失败',
      });
      throw error;
    }
  },

  // 证书相关Actions
  fetchCertificates: async () => {
    try {
      set({ certificatesLoading: true, certificatesError: null });
      const certificates = await apiService.getCertificates();
      set({ certificates, certificatesLoading: false });
    } catch (error: any) {
      set({
        certificatesLoading: false,
        certificatesError: error.message || '获取证书列表失败',
      });
    }
  },

  createCertificate: async (certData: CreateCertificateRequest) => {
    try {
      set({ certificatesLoading: true, certificatesError: null });
      const newCert = await apiService.createCertificate(certData);
      const { certificates } = get();
      set({
        certificates: [...certificates, newCert],
        certificatesLoading: false,
      });
      return newCert;
    } catch (error: any) {
      set({
        certificatesLoading: false,
        certificatesError: error.message || '创建证书失败',
      });
      throw error;
    }
  },

  updateCertificate: async (id: number, certData: Partial<CreateCertificateRequest>) => {
    try {
      set({ certificatesLoading: true, certificatesError: null });
      const updatedCert = await apiService.updateCertificate(id, certData);
      const { certificates } = get();
      set({
        certificates: certificates.map((cert) => (cert.id === id ? updatedCert : cert)),
        certificatesLoading: false,
      });
      return updatedCert;
    } catch (error: any) {
      set({
        certificatesLoading: false,
        certificatesError: error.message || '更新证书失败',
      });
      throw error;
    }
  },

  deleteCertificate: async (id: number) => {
    try {
      set({ certificatesLoading: true, certificatesError: null });
      await apiService.deleteCertificate(id);
      const { certificates } = get();
      set({
        certificates: certificates.filter((cert) => cert.id !== id),
        certificatesLoading: false,
      });
    } catch (error: any) {
      set({
        certificatesLoading: false,
        certificatesError: error.message || '删除证书失败',
      });
      throw error;
    }
  },

  // 容器相关Actions
  fetchContainers: async () => {
    try {
      set({ containersLoading: true, containersError: null });
      const containers = await apiService.getContainers();
      set({ containers, containersLoading: false });
    } catch (error: any) {
      set({
        containersLoading: false,
        containersError: error.message || '获取容器列表失败',
      });
    }
  },

  createContainer: async (containerData: CreateContainerRequest) => {
    try {
      set({ containersLoading: true, containersError: null });
      const newContainer = await apiService.createContainer(containerData);
      const { containers } = get();
      set({
        containers: [...containers, newContainer],
        containersLoading: false,
      });
      return newContainer;
    } catch (error: any) {
      set({
        containersLoading: false,
        containersError: error.message || '创建容器失败',
      });
      throw error;
    }
  },

  updateContainer: async (id: number, containerData: Partial<CreateContainerRequest>) => {
    try {
      set({ containersLoading: true, containersError: null });
      const updatedContainer = await apiService.updateContainer(id, containerData);
      const { containers } = get();
      set({
        containers: containers.map((container) => (container.id === id ? updatedContainer : container)),
        containersLoading: false,
      });
      return updatedContainer;
    } catch (error: any) {
      set({
        containersLoading: false,
        containersError: error.message || '更新容器失败',
      });
      throw error;
    }
  },

  deleteContainer: async (id: number) => {
    try {
      set({ containersLoading: true, containersError: null });
      await apiService.deleteContainer(id);
      const { containers } = get();
      set({
        containers: containers.filter((container) => container.id !== id),
        containersLoading: false,
      });
    } catch (error: any) {
      set({
        containersLoading: false,
        containersError: error.message || '删除容器失败',
      });
      throw error;
    }
  },

  // 仪表板统计Actions
  fetchDashboardStats: async () => {
    try {
      set({ statsLoading: true, statsError: null });
      const dashboardStats = await apiService.getDashboardStats();
      set({ dashboardStats, statsLoading: false });
    } catch (error: any) {
      set({
        statsLoading: false,
        statsError: error.message || '获取统计数据失败',
      });
    }
  },

  // 清除错误
  clearErrors: () => {
    set({
      sitesError: null,
      certificatesError: null,
      containersError: null,
      statsError: null,
    });
  },
})); 